<template>
  <div>
  <a-row :gutter="10">
    <a-col :md="7" :sm="24">
      <a-card :bordered="false">

        <!-- 按钮操作区域 -->
        <a-row style="margin-left: 14px">
          <a-button @click="handleAdd" type="primary">添加配置</a-button>
        </a-row>

        <div style="background: #fff;padding-left:16px;height: 100%; margin-top: 5px">

          <!-- 树-->
          <a-col :md="10" :sm="24">
            <template>
              <a-dropdown :trigger="[this.dropTrigger]" @visibleChange="dropStatus">
               <span style="user-select: none">
            <a-tree
              id="tree"
              multiple
              @select="onSelect"
              @check="onCheck"
              :show-icon="true"
              @rightClick="rightHandle"
              :selectedKeys="selectedKeys"
              :checkedKeys="checkedKeys"
              :treeData="treeData"
              :expandedKeys="iExpandedKeys"
              :autoExpandParent="autoExpandParent"
              @expand="onExpand">
               </a-tree>
                </span>
                <a-menu slot="overlay">
                  <a-menu-item @click="copy" key="1">复制</a-menu-item>
                  <a-menu-item @click="copyTo" v-show='copyed' key="2">粘贴</a-menu-item>
                  <a-menu-item @click="closeDrop" key="3">取消</a-menu-item>
                </a-menu>
              </a-dropdown>
            </template>
          </a-col>
        </div>
      </a-card>
    </a-col>
    <a-col :md="15" :sm="24">
      <a-card :bordered="false">
      </a-card>
    </a-col>

    <a-col :md="14" :sm="24">
      <a-card>
              <a-button title="删除多条数据" @click="batchDel" type="primary" style='margin-bottom: 10px'>批量删除</a-button>

      <a-table
        size="small"
        bordered
        rowKey="id"

        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :scroll="{ y: 240 }"
        :rowSelection="{selectedRowKeys: selectedRowKeys,onSelectAll:onSelectAll, onChange: onSelectChange}"
      >
        <span slot="action" slot-scope="text, record">
           <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical"/>
              <a>
                <a-popconfirm title="确定删除吗?" @confirm="() => deleteConf(record)">
                      <a>删除</a>
                    </a-popconfirm>
              </a>
            </span>
      </a-table>
      </a-card>
    </a-col>
  </a-row>
    <add-conf-modal ref='addConfModal'  @ok='addOk'></add-conf-modal>
  </div>
</template>

<script>
import { deleteAction, getAction } from '@api/manage'
import { queryDeviceTreeList } from '@api/api'
import pick from 'lodash.pick'
import AddConfModal from '@views/passage/device/modules/AddConfModal'

export default {
  name: 'deviceConfTree',
  components:{
    AddConfModal
  },
  data(){
    return{

      rowSelectionL:[],
      id:"",
      queryParam:{},
      confirmLoading:false,
      labelCol: {
        xs: {span: 24},
        sm: {span: 5}
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16}
      },
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '配置编号',
          align: 'center',
          dataIndex: 'id'
        },
        {
          title: '配置类型',
          align: 'center',
          customRender: x => ('1' == x ? '时间段配置' : '节假日配置'),
          dataIndex: 'type'
        },
        {
          title: '配置状态',
          align: 'center',
          customRender: x => ('1' == x ? '在用' : '停用'),
          dataIndex: 'status'
        },
        {
          title:'配置值',
          align:'center',
          dataIndex: 'configValue'
        },
        {
          title:'开始时间',
          align: 'center',
          dataIndex: 'startTime'
        },
        {
          title: '结束时间',
          align:'center',
          dataIndex: 'endTime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: {customRender: 'action'},
          align: 'center',
        },
      ],
      dataSource:[],
      dataSource2:[],
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      deviceConf:{},
      loading: false,
      selectedRowKeys: [],
      form: this.$form.createForm(this),
      currSelected: {},
      dropTrigger: '',
      selectedKeys:[],
      checkedKeys: [],
      treeData: [],
      iExpandedKeys: [],
      autoExpandParent: true,
      url:{
        findConf:'/deviceConf/findConf',
        deleteBatch:'/deviceConf/delBatch',
        deleteConf:'/deviceConf/delConf',
        copyConf:'/deviceConf/copyConf',

      },
      isDevice:1,
      copyDeviceId:'',
      copyedDeviceId:'',
      deviceId:'',
      dataSource3:[],
      copyed:false,

    }
  },
  created() {
    this.loadTree()
  },
  methods:{
    copy(node){
      this.copyDeviceId = this.deviceId
      this.copyed=true

    },
    copyTo(){
      this.copyedDeviceId = this.deviceId
      if (this.copyedDeviceId==this.copyDeviceId){
        this.$message.warn ("不能粘贴自己")
      }else{
        getAction(this.url.copyConf,{copyDeviceId:this.copyDeviceId,copyedDeviceId:this.copyedDeviceId}).then((res)=>{
          if (res.success){
            this.$message.success("复制配置成功")
            this.onSelect(this.selectedKeys, this.rightNode)
          }else{
            this.$message.warn("复制配置失败")
          }
        })
      }

    },
    // 右键操作方法
    rightHandle(node) {
      this.rightNode = node
      this.isDevice = node.node.dataRef.isDevice
      if (this.isDevice===1){
        this.dropTrigger = 'contextmenu'
        this.rightClickSelectedKey = node.node.eventKey
          this.deviceId = node.node.dataRef.key
      }


    },
    onSelectAll(selected, selectedRows, changeRows) {
      if (selected === true) {
        for (var a = 0; a < changeRows.length; a++) {
          this.dataSource2.push(changeRows[a])
        }
      } else {
        for (var b = 0; b < changeRows.length; b++) {
          this.dataSource2.splice(this.dataSource2.indexOf(changeRows[b]), 1)
        }
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectedRows
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      // console.log(sorter);
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    },

    handleAdd() {
        let key = this.currSelected.key
        if (!key) {
          this.$message.warning('请先选中一个设备!')
          return false
        }
        this.$refs.addConfModal.setDeviceId(this.deviceConf)
        this.$refs.addConfModal.title = '新增配置'
    },
    handleEdit(record){
      this.$refs.addConfModal.title="编辑配置"
      this.$refs.addConfModal.setDevice(record)
    },
    batchDel: function () {
      if (this.checkedKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
      } else {
        var ids = ''
        for (var a = 0; a < this.checkedKeys.length; a++) {
          ids += this.checkedKeys[a] + ','
        }
        var that = this
        this.$confirm({
          title: '确认删除',
          content: '确定要删除所选中的 ' + this.checkedKeys.length + ' 条数据?',
          onOk: function () {
            deleteAction(that.url.deleteBatch, {ids: ids}).then((res) => {
              if (res.success) {
                that.$message.success(res.data)
                that.loadTree()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            })
          }
        })
      }
    },
    deleteConf(record){
      deleteAction(this.url.deleteConf,{id:record.id}).then((res)=>{
        if (res.success){
          this.$message.success(res.message)
          this.setValuesToTable(this.currSelected.key)
          this.onClearSelected()
        }else {
          this.$message.warning(res.message)
        }
      })
    },
    onClearSelected() {
      this.hiding = true
      this.checkedKeys = []
      this.currSelected = {}
      this.form.resetFields()
      this.selectedKeys = []
    },
    clone(){

    },
    closeDrop() {
      this.dropTrigger = ''
    },
    // 右键点击下拉框改变事件
    dropStatus(visible) {
      if (visible == false) {
        this.dropTrigger = ''
      }
    },
    addOk(){
        this.setValuesToTable(this.currSelected.key)
    },
    onCheck(checkedKeys, info) {
      this.checkedKeys = checkedKeys
      let iExpandedKeys = Object.assign([], checkedKeys)
      this.pushAllParentKey(iExpandedKeys)
      this.iExpandedKeys = iExpandedKeys
      this.selectedKeys = []
      this.autoExpandParent = false
    },
    // 触发onSelect事件时,为区域树右侧的form表单赋值
    setValuesToForm(record) {
      this.form.getFieldDecorator('fax', {initialValue: ''})
      this.form.setFieldsValue(pick(record, 'name', 'sort', 'status', 'areaCode', 'remark'))
    },
    onSelect(selectedKeys, e) {
      this.hiding = false
      let record = e.node.dataRef
      let isDevice = record.isDevice
      this.currSelected = Object.assign({}, record)
      this.model = this.currSelected
      if (isDevice===1){
        this.selectedKeys = [record.key]
        this.currSelected.key = record.id
        this.deviceConf.id = record.id
        this.deviceConf.name = record.title
        this.setValuesToTable(record.id)
      }else{
          this.dataSource=[]
      }


    },
    setValuesToTable(deviceId){
      let id = ""+deviceId;
      // console.log(id)
        getAction(this.url.findConf+"?id="+id).then((res)=>{
          if (res.success){
            this.dataSource=res.result.records;
            this.ipagination.total = res.result.total
            this.ipagination.current = res.result.current
          }else{
              this.$message.warning(res.message)
          }
        })
    },
    getCurrSelectedTitle() {
      return !this.currSelected.title ? '' : this.currSelected.title
    },
    onExpand(expandedKeys) {
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.iExpandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    loadTree() {
      let that = this
      that.treeData = []
      queryDeviceTreeList().then((res) => {
        if (res.success&&res.result.length>0) {
          for (let i = 0; i < res.result.length; i++) {
            let temp = res.result[i]
            that.treeData.push(temp)
            // that.setThisExpandedKeys(temp)
          }
          this.loading = false
        }
      })
    },
  }
}
</script>

<style scoped>

</style>